#include "rc.h"

#include <sys/stat.h>

void usrstat_start(void)
{
FILE *f;
char *s = "/tmp/ipt_userstat.sh";
char *g,*buf,*i,*mac,*ip,*desc,*p,*router_ip;
char lan[24];
char *argv[3];
int pid;
router_ip = nvram_safe_get("lan_ipaddr");
strlcpy(lan, router_ip, sizeof(lan));
if ((p = strrchr(lan, '.')) != NULL) *(p + 1) = 0;
if ((f = fopen(s, "w")) == NULL) return;
fprintf(f,"#!/bin/sh\n"
	"iptables -N download\n"
	"iptables -N upload\n"
	"iptables -I FORWARD 1 -j download\n"
	"iptables -I FORWARD 2 -j upload\n"
	);
g = buf = strdup(nvram_safe_get("dhcpd_static"));
while (g) {
if ((p = strsep(&g, ">")) == NULL) break;
		i = vstrsep(p, "<", &mac, &ip, &desc);
fprintf(f,"iptables -A download -d %s%s ! -s %s\n",lan,ip,router_ip);
fprintf(f,"iptables -A upload -s %s%s ! -d %s\n",lan,ip,router_ip);
}
free(buf);
fclose(f);
chmod(s, 0700);
chdir("/tmp");
argv[0] = s;
	argv[1] = NULL;
	argv[2] = NULL;
	if (_eval(argv, NULL, 0, &pid) != 0) {
		pid = -1;
	}
	else {
		kill(pid, 0);
	}
			
	chdir("/");
}

void usrstat_stop(void)
{
FILE *f,*f2;
char *cdown,*cup,*ip,*s;
char *filett = "/tmp/exit";
if ((f = popen("iptables -L download -vnx", "r")) != NULL) {
 while (fgets(s, sizeof(s), f)) {
if(sscanf(s, "%s %s %*s %*s %*s %*s %*s %s", cdown, cup, ip) == 3) {
if ((f2 = fopen(filett, "w")) == NULL) return;
fprintf(f2,"Test: %s %s %s",cdown,cup,ip);
fclose(f2);
cprintf("Test: %s %s %s",cdown,cup,ip);
}
}

}
pclose(f);
}
